/*
 * util.c
 *
 *  Created on: Nov 28, 2010
 *      Author: cumeo89
 */

#include <stdlib.h>
#include <string.h>
#include "util.h"

glong g_unichar_strlen(gunichar *s) {
	gunichar *p;
	for (p = s; *p != 0 && *p < 0x80000000; p++);
	return p-s;
}

Ucs4String **utf8ToUcs4All(const gchar **strings) {
	GPtrArray *stringArr = g_ptr_array_new();
	int i;
	for (i = 0; strings[i] != NULL; i++) {
		const gchar *utf8String = strings[i];
		Ucs4String *ucs4String = g_new(Ucs4String, 1);
		ucs4String->s = g_utf8_to_ucs4_fast(utf8String, -1, &ucs4String->m);
		ucs4String->s[ucs4String->m] = 0x80000000 | i;
		ucs4String->m++;
		g_ptr_array_add(stringArr, ucs4String);
	}
	g_ptr_array_add(stringArr, NULL);
	return (Ucs4String **)g_ptr_array_free(stringArr, FALSE);
}

int pointerArrSize(void *parr) {
	int i = 0;
	while (((void **)parr)[i] != NULL) {
		i++;
	}
	return i;
}

gchar *utf8_substring(const gchar* str, glong startOffset, glong endOffset) {
	gchar *s = g_utf8_offset_to_pointer(str, startOffset);
	gchar *e = g_utf8_offset_to_pointer(s, endOffset - startOffset + 1);
	int utf8_length = e - s;
	gchar *substr = malloc(utf8_length + 1);
	memcpy(substr, s, utf8_length);
	if (substr[utf8_length-1] == 0) {
		substr[utf8_length-1] = '$';
	}
	substr[utf8_length] = 0;
	return substr;
}
